package dz.chuxin.app.core;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Fragment基类
 * 支持ViewPager中的Fragment延迟加载
 * Created by chuxin on 2016/7/2.
 */
public abstract class BaseFragment extends Fragment {

    private boolean isLazyLoadEnabled;
    private boolean isDataInitialized;
    private boolean isVisibleToUser;
    private boolean isViewInitialized;

    // 启用延迟加载
    public void enableLazyLoad() {
        isLazyLoadEnabled = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        checkAndLoadData();
    }

    private void checkAndLoadData() {
        if (isVisibleToUser && isViewInitialized && !isDataInitialized) {
            isDataInitialized = true;
            setUpData();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!isLazyLoadEnabled) {
            setUpView(view);
            setUpData();
            return;
        }
        setUpView(view);
        isViewInitialized = true;
        if (savedInstanceState != null)
            onRestoreInstanceState(savedInstanceState);

        if (isDataInitialized) setUpData();
        else checkAndLoadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isViewInitialized = false;
    }

    // 恢复状态保存
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        isDataInitialized = true;
    }

    // 建立起界面视图结构
    protected abstract void setUpView(View view);

    // 建立数据结构
    protected abstract void setUpData();
}
